<?php
/**
 * client 客户端核心类
 * @author quanhengzhuang
 */
class client {
	/**
	 * 命令
	 * @var string
	 */
	private $command = '';
	
	/**
	 * 新命令
	 * @var bool
	 */
	public $new_command = true;
	
	/**
	 * 结果
	 * @var string
	 */
	private $result = '';
	
	/**
	 * 结果
	 * @var bool
	 */
	public $new_result = true;
	
	/**
	 * 接收命令
	 */
	public function receive_command() {
		$send_url = SERVER.'/run.php?action=send_command&cid='.CLIENT_ID;
		
		//接收
		$command = trim(file_get_contents($send_url));
		
		//是否新命令
		$this->new_command = ($command != $this->command);
		
		$this->command = $command;
	}
	
	/**
	 * 执行命令
	 * @param bool $force 是否强制执行
	 */
	public function execute($force = false) {
		if($force || $this->new_command) {
			$this->command == '' ? ($result = array('Empty Command!')) : exec($this->command, $result);
			$result = json_encode($result);
			
			//是否新结果
			$this->new_result = ($result != $this->result);
			
			//写入新结果
			$this->result = $result;
		}
	}
	
	/**
	 * 发送结果
	 */
	public function send_result($force = false) {
		if($force || $this->new_result) {
			$receive_url = SERVER.'/run.php?action=receive_result&cid='.CLIENT_ID;
			
			//发送参数
			$options = array(
				'http' => array(
					'method' => 'POST',
					'header' => 'Content-type: application/x-www-form-urlencoded',
					'content' => http_build_query(array('result' => $this->result,)),
				),
			);
			$context = stream_context_create($options);
			
			//发送
			file_get_contents($receive_url, false, $context);
		}
	}
}
?>